package middleware

import (
	"context"
	v1 "eag_arch_layout/api/baseArch/v1"
	"eag_arch_layout/internal/conf"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/selector"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/gorilla/handlers"
)

// CreateMiddleWare 生成中间的配置信息
//
//	使用方法：在需要server/http 中加入 ：opts := middleware.CreateMiddleWare(c, j, logger)
func CreateMiddleWare(_ *conf.Server, j *conf.Jwt, logger log.Logger) []http.ServerOption {
	whiteList := make(map[string]bool) // 无需验证token的接口
	whiteList[v1.OperationSysLogin] = true
	var opts = []http.ServerOption{
		http.Middleware(

			recovery.Recovery(),
			selector.Server(JwtAuth2HeaderMw(j, logger)).Match(func(ctx context.Context, operation string) bool {
				if _, ok := whiteList[operation]; ok {
					return false
				}
				return true
			}).Build(),
			CreateQueryMapFromBody(logger),
			//CorsMw(logger),
			//selector.Server(CreateQueryMapFromBody(logger)).Build(),
		),

		//http.ErrorEncoder(DefaultErrorEncoder),
		//http.ResponseEncoder(DefaultResponseEncoder),
		http.NotFoundHandler(NotFoundOrMethodNotAllowedHandler(404, logger)),
		http.MethodNotAllowedHandler(NotFoundOrMethodNotAllowedHandler(405, logger)),
		http.Filter(handlers.CORS(
			handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
			handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE"}),
			handlers.AllowedOrigins([]string{"*"}),
		)),
	}
	// 错误响应封装`-myself
	opts = append(opts, http.ErrorEncoder(EncoderError(logger)))

	return opts
}
